package org.ruiyichen.guizhou.agr.base;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;

import org.ruiyichen.guizhou.agr.bean.mode.User;
import org.ruiyichen.guizhou.agr.config.Constant;
import org.ruiyichen.guizhou.agr.utils.L;
import org.ruiyichen.guizhou.agr.utils.StrUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Observable;

/**
 * 全局数据管理类
 * 作者：Administrator
 * 邮箱：wutian8489@foxmail.com
 */
public class DataManger extends Observable {


    private volatile static DataManger instance;

    private DataManger() {
    }

    public static DataManger getInstance() {
        if (instance == null) {
            synchronized (DataManger.class) {
                if (instance == null) {
                    instance = new DataManger();
                }
            }
        }
        return instance;
    }

    private Context mContext;

    private final User mUserInfo = new User();

    public void init(Context context) {
        mContext = context;
        getUserInfo(mContext);
    }

    public void setUserInfo(User userInfo) {
        if (userInfo != null) {
            synchronized (mUserInfo) {
                Field[] fields = userInfo.getClass().getDeclaredFields();
                Field[] mFields = mUserInfo.getClass().getDeclaredFields();
                Field.setAccessible(fields, true);
                Field.setAccessible(mFields, true);
                for (int i = 0; i < fields.length; i++) {
                    try {
                        Object obj = fields[i].get(userInfo);
                        if (fields[i].getType() == int.class) {
                            if (obj != null) {
                                mFields[i].set(mUserInfo, Integer.parseInt(obj.toString()));
                            }
                        } else if (fields[i].getType() == String.class) {
                            if (obj != null)
                                mFields[i].set(mUserInfo, String.valueOf(obj));
                        }
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }

//                if (StrUtil.isNotEmpty(userInfo.getUser_id()))
//                    mUserInfo.setUser_id(userInfo.getUser_id());
//                if (mUserInfo.getIs_new_user() != userInfo.getIs_new_user())
//                    mUserInfo.getIs_new_user(userInfo.setIs_new_user());
//                if (StrUtil.isNotEmpty(userInfo.getBalance()))
//                    mUserInfo.setBalance(userInfo.getBalance());
//                if (StrUtil.isNotEmpty(userInfo.getImg_url()))
//                    mUserInfo.setImg_url(userInfo.getImg_url());
//                if (mUserInfo.getIs_pay_pwd() != userInfo.getIs_pay_pwd())
//                    mUserInfo.setIs_pay_pwd(userInfo.getIs_pay_pwd());
//                if (StrUtil.isNotEmpty(userInfo.getPhone()))
//                    mUserInfo.setPhone(userInfo.getPhone());
//                if (StrUtil.isNotEmpty(userInfo.getUser_name()))
//                    mUserInfo.setUser_name(userInfo.getUser_name());
            }
        }
        saveUserInfo(mContext, mUserInfo);
    }

    /**
     * 保存账户信息需要初始化
     *
     * @param context
     * @param userInfo
     */
    private void saveUserInfo(Context context, User userInfo) {
        SharedPreferences userSp = context.getSharedPreferences(Constant.File.USER_INFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor userEditor = userSp.edit();

        Field[] fields = userInfo.getClass().getDeclaredFields();
        Field.setAccessible(fields, true);
        for (int i = 0; i < fields.length; i++) {
            try {
                if (fields[i].getType() == int.class) {
                    int value = (int) fields[i].get(userInfo);
                    userEditor.putInt(fields[i].getName(), value);
                } else if (fields[i].getType() == String.class) {
                    String value = (String) fields[i].get(userInfo);
                    userEditor.putString(fields[i].getName(), value);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        userEditor.commit();

        L.e(new Gson().toJson(userInfo));
//        notifyObservers();
        setChanged();
        notifyObservers(mUserInfo);
    }

    public boolean hasLogin(Context context) {
        String userStr = context.getSharedPreferences(Constant.File.USER_INFO, Context
                .MODE_PRIVATE).getString("token", "");
        return StrUtil.isNotEmpty(userStr);
    }

    public boolean hasLogin() {
        return StrUtil.isNotEmpty(mUserInfo.token);
    }

    /**
     * 获取登录信息并刷新数据
     *
     * @param context
     */
    public void getUserInfo(Context context) {
        SharedPreferences user = context.getSharedPreferences(Constant.File.USER_INFO, Context.MODE_PRIVATE);

        Field[] fields = mUserInfo.getClass().getDeclaredFields();
        Field.setAccessible(fields, true);
        for (int i = 0; i < fields.length; i++) {
            try {
                if (fields[i].getType() == int.class) {
                    fields[i].set(mUserInfo, user.getInt(fields[i].getName(), 0));
                } else if (fields[i].getType() == String.class) {
                    fields[i].set(mUserInfo, user.getString(fields[i].getName(), ""));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        L.e("getUserInfo" + new Gson().toJson(mUserInfo));
    }

    /**
     * 获取登录信息
     *
     * @return
     */
    public User getUserInfo() {
        return mUserInfo;
    }

    /**
     * 退出登录
     */
    public void logout(Context context) {
        Field[] fields = mUserInfo.getClass().getDeclaredFields();
        Field.setAccessible(fields, true);
        for (int i = 0; i < fields.length; i++) {
            try {
                if (fields[i].getType() == int.class) {
                    fields[i].set(mUserInfo, 0);
                } else if (fields[i].getType() == String.class) {
                    fields[i].set(mUserInfo, "");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        saveUserInfo(context, mUserInfo);
    }

    /**
     * 拼接某属性get 方法
     *
     * @param fldname
     * @return
     */
    public static String pareGetName(String fldname) {
        if (null == fldname || "".equals(fldname)) {
            return null;
        }
        String pro = "get" + fldname.substring(0, 1).toUpperCase() + fldname.substring(1);
        return pro;
    }

    /**
     * 拼接某属性set 方法
     *
     * @param fldname
     * @return
     */
    public static String pareSetName(String fldname) {
        if (null == fldname || "".equals(fldname)) {
            return null;
        }
        String pro = "set" + fldname.substring(0, 1).toUpperCase() + fldname.substring(1);
        return pro;
    }

    /**
     * 判断该方法是否存在
     *
     * @param methods
     * @param met
     * @return
     */
    public static boolean checkMethod(Method methods[], String met) {
        if (null != methods) {
            for (Method method : methods) {
                if (met.equals(method.getName())) {
                    return true;
                }
            }
        }
        return false;
    }

}
